package com.debao.quartz.task;


import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.debao.common.constant.VipConstants;
import com.debao.common.constant.WechatConstants;
import com.debao.common.utils.AliyunSmsUtil;
import com.debao.common.utils.StringUtils;
import com.debao.system.domain.UserCard;
import com.debao.system.service.IConfigService;
import com.debao.system.service.ISysUserService;
import com.debao.system.service.IUserCardService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 每天更新过期的会员账号
 */
@Component("vipCardTask")
public class VipCardTask {

    @Resource
    private IUserCardService userCardService;
    @Resource
    private IConfigService configService;
    @Resource
    private ISysUserService userService;

    // 会员过期少于多少天发送提醒
    private static long delay = 5;

    /**
     * 更新账号状态
     */
    public void updateStatus() {
        // 获取所有没有过期的账号
        List<UserCard> userCards = userCardService.selectUserCardList(new UserCard().setStatus(VipConstants.NORMAL));
        //读取配置项
        String setting_Day = configService.selectValueByKey(WechatConstants.VIP_DATE);
        if (StringUtils.isNotEmpty(setting_Day)) {
            delay = Long.parseLong(setting_Day);
        }
        // 遍历列表，更新过期的会员账号状态
        for (UserCard userCard : userCards) {
            try {
                // 比较当前时间与过期时间
                int compare = DateUtil.compare(new Date(), DateUtil.parse(userCard.getEndAt(), "yyyy-MM-dd"), "yyyy-MM-dd");
                if (compare > 0) { // 已经过期
                    // 更新状态
                    userCard.setStatus(VipConstants.EXPIRE);
                    updateUserCardSafely(userCard);
                }
                //计算还有多少天过期
                long phaseDay = DateUtil.betweenDay(new Date(), DateUtil.parse(userCard.getEndAt(), "yyyy-MM-dd"), false);
                if (phaseDay <= delay){
                    //快过期的短信通知
                    sendMsg(userCard);
                }
            } catch (DateException e) {
                // 处理日期解析异常
                System.err.println("日期解析错误: " + e.getMessage());
            }
        }
    }
    private void sendMsg(UserCard userCard) {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            try {
                // 获取用户手机号码
                String phone = userService.getPhoneByUserId(userCard.getUserId());
                if (!phone.isEmpty()) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("endAt", userCard.getEndAt());
                    AliyunSmsUtil.sendSms(phone, "SMS_471735226", JSONObject.toJSONString(map));
                }
            } catch (Exception e) {
                // 记录异常
                System.err.println("发送短信失败: " + e.getMessage());
            } finally {
                // 关闭 ExecutorService
                executor.shutdown();
            }
        });
    }

    // 原子性更新用户卡片状态的方法
    private synchronized void updateUserCardSafely(UserCard userCard) {
        try {
            userCardService.updateUserCard(userCard);
        } catch (Exception e) {
            // 处理更新过程中的异常
            System.err.println("更新用户卡片状态失败: " + e.getMessage());
        }
    }
}
